import { useEffect, useRef } from 'react'
import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Select,
  DatePicker,
  Table,
  Tag,
  Image,
  Space,
  Popconfirm,
  message,
} from 'antd'
import { useDispatch, useSelector } from 'react-redux'
import { Link, useHistory } from 'react-router-dom'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons'
import styles from './index.module.scss'
import {
  getChannelList,
  getArticleList,
  delArticle,
} from '@/store/actions/article'
import img from '@/assets/error.png'
const { RangePicker } = DatePicker

const STATUS = [
  { id: -1, title: '全部', color: 'magenta' },
  { id: 0, title: '草稿', color: 'red' },
  { id: 1, title: '待审核', color: 'volcano' },
  { id: 2, title: '审核通过', color: 'lime' },
  { id: 3, title: '审核失败', color: 'gold' },
]

export default function Article() {
  const history = useHistory()
  const dispatch = useDispatch()
  const channels = useSelector((state) => state.article.channels)
  const articles = useSelector((state) => state.article.articles)
  const params = useRef({})
  useEffect(() => {
    dispatch(getChannelList())
    dispatch(getArticleList())
  }, [dispatch])
  const onFinish = (values) => {
    if (values.status !== -1) {
      params.current.status = values.status
    }
    if (values.channel_id) {
      params.current.channel_id = values.channel_id
    }
    if (values.date) {
      params.current.begin_pubdate = values.date[0]
        .startOf('day')
        .format('YYYY-MM-DD HH:mm:ss')
      params.current.end_pubdate = values.date[1]
        .endOf('day')
        .format('YYYY-MM-DD HH:mm:ss')
    }
    params.current.page = 1
    dispatch(getArticleList(params.current))
  }
  // #2
  const del = async (id) => {
    await dispatch(delArticle(id))
    await dispatch(getArticleList(params.current))
    message.success('删除成功')
  }
  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      key: 'cover',
      render(cover) {
        if (cover.type === 0) {
          return <Image width={200} height={150} src={img} />
        } else {
          return (
            <Image
              width={200}
              height={150}
              src={cover.images[0]}
              fallback={img}
            />
          )
        }
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => {
        const obj = STATUS.find((item) => item.id === status)
        return <Tag color={obj.color}>{obj.title}</Tag>
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
      key: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
      key: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
      key: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
      key: 'like_count',
    },
    {
      title: '操作',
      dataIndex: 'id',
      key: 'id',
      render(id) {
        return (
          <Space>
            <Button
              type='primary'
              shape='circle'
              icon={<EditOutlined />}
              onClick={() => history.push(`/home/publish/${id}`)}
            ></Button>
            {/* #1 */}
            <Popconfirm title='确定要删除该文章吗？' onConfirm={() => del(id)}>
              <Button
                type='primary'
                shape='circle'
                danger
                icon={<DeleteOutlined />}
              ></Button>
            </Popconfirm>
          </Space>
        )
      },
    },
  ]
  return (
    <div className={styles.root}>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to='/home'>首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>内容管理</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          initialValues={{
            status: -1,
          }}
          onFinish={onFinish}
        >
          <Form.Item label='状态' name='status'>
            <Radio.Group>
              {STATUS.map((item) => (
                <Radio key={item.id} value={item.id}>
                  {item.title}
                </Radio>
              ))}
            </Radio.Group>
          </Form.Item>
          <Form.Item label='频道' name='channel_id'>
            <Select style={{ width: 200 }} placeholder='请选择频道'>
              {channels.map((item) => (
                <Select.Option key={item.id} value={item.id}>
                  {item.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label='日期' name='date'>
            <RangePicker />
          </Form.Item>
          <Form.Item>
            <Button type='primary' htmlType='submit'>
              筛选
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <Card
        title={`根据筛选条件共查询到 ${articles.total_count} 条结果`}
        style={{ marginTop: 10 }}
      >
        <Table
          rowKey='id'
          dataSource={articles.results}
          columns={columns}
          pagination={{
            position: ['bottomCenter'],
            total: articles.total_count,
            pageSize: articles.per_page,
            current: articles.page,
            onChange(page, pageSize) {
              params.current.page = page
              params.current.per_page = pageSize
              dispatch(getArticleList(params.current))
            },
          }}
        />
      </Card>
    </div>
  )
}
